<?php

namespace api\controllers;

use common\models\Shop;
use common\models\AttributeValue;
use common\models\UserCollection;
use common\service\ActiveService;
use common\service\CommonService;
use common\models\Goods;
use common\models\Address;
use common\models\User;
use common\models\Group;
use common\models\Order;
use common\service\ConstantService;
use common\models\GoodsImg;
use common\models\Active;
use common\models\ActiveAttr;
use common\service\GoodsService;
use common\service\GlobalUrlService;

class ActiveController extends BaseController
{

    /**
     * 拼团详情页
     */
    public function actionGetActivityInfo(){
        if($this->isGet()) {
            $collction_data = [];
            $aid = $this->get('aid');
            $collction_data['list_id'] = $aid;
            $collction_data['user_id'] = $this->user['id'];
            $collction_data['type'] = 0;
            $collction_data['status'] = 0;
            $collction_data['create_time'] = time();
            $collction_data['update_time'] = time();
            //存储查看历史
            UserCollection::addCollection($collction_data);

            if (!$aid) {
                return $this->renderJson([], '缺少参数', ConstantService::$response_fail);
            }
            $act = Active::find()->where(['id' => $aid])->asArray()->one();
            $act['goods_img'] = GlobalUrlService::buildCdnUrl($act['goods_img']);
            $collect = UserCollection::findOne(['type'=>0,'list_id'=>$aid,'user_id'=>$this->user['id'],'status'=>1]);
            if(isset($collect) && !empty($collect)){
                $act['collect'] = 1;
            } else {
                $act['collect'] = 0;
            }
            //商品
            $act['goods'] = Goods::find()->select('id,list_img,introduction')->where(['id' => $act['goods_id']])->asArray()->one();
            $act['goods']['list_img'] = GlobalUrlService::buildCdnUrl($act['goods']['list_img']);
            //商品图片
            $goodsimg = GoodsImg::find()->select('img_url')->where(['goods_id' => $act['goods_id'], 'status' => 1])->asArray()->all();
            foreach ($goodsimg as &$val){
                $val['img_url'] = GlobalUrlService::buildCdnUrl($val['img_url']);
            }
            $act['goods']['banner'] = $goodsimg;
            //活动总库存
            $attr = ActiveAttr::find()->select('inventory,original_price,collage_price')->where(['active_id' => $aid])->asArray()->all();
            $act['active_count'] = 0;
            $act['max_price'] = 0;
            $act['min_price'] = 0;
            if(isset($attr) && !empty($attr)){
                $inventory = 0;
                $original_price = array_column($attr,'original_price');
                $collage_price = array_column($attr,'collage_price');
                foreach ($attr as $row){
                    $inventory += $row['inventory'];
                }
                $act['active_count'] = $inventory;
                $act['max_price'] = max($original_price);
                $act['min_price'] = min($collage_price);
            }
//            //已拼团多少件
//            $goodsCount = Order::find()->select('sum(goods_num) as goods_num')->where(['goods_id' => $act['goods_id'], 'pay_status' => 1])->asArray()->one();
//            if ($goodsCount['goods_num']) {
//                $act['goods_sum'] = $goodsCount['goods_num'];
//            } else {
//                $act['goods_sum'] = 0;
//            }
            $shopdata = $this->_GetShopInfo($act['shop_id']);

            $act['shop'] = $shopdata;
            if ($act['status'] == 1 && $act['is_del'] == 0) {
                return $this->renderJson($act, '', ConstantService::$response_success);
            }
            return $this->renderJson($act, '该活动不存在或已结束', ConstantService::$response_fail);
        }
        return $this->renderJson([],'该活动不存在或已结束',ConstantService::$response_fail);
    }

    /**
     * 详情页参团人
     * @param $id
     * @return mixed
     */
    public function actionGetGroupList(){
        if($this->isGet()) {
            $id = $this->get('aid');
            $group = Group::find()->select('complete_time,status,launch_id,id,group_num,current_group_num,create_time,expire_time')
                ->andwhere(['active_id' => $id])
                ->andwhere(['!=', 'status', 0])
                ->orderBy(['status' => SORT_DESC, 'create_time' => SORT_DESC])
                ->asArray()
                ->all();

            $groupArr = [];

            if (!empty($group)) {
                $group_one = $group[0];
                if(($group_one['group_num']-$group_one['current_group_num']) > 0){
                    $oneuser = User::find()->select('nickname,avatarurl')->where(['id' => $group_one['launch_id']])->asArray()->one();
                    $oneuser['nickname'] = $oneuser['nickname'] ? base64_decode($oneuser['nickname']) : '匿名用户';
                    $oneuser['avatarurl'] = GlobalUrlService::buildCdnUrl($oneuser['avatarurl']);
                    $group_one['users'] = $oneuser;
                    $group_one['group_end'] = $group[0]['group_num'] - $group[0]['current_group_num'];

                    $time = time();
                    $group_one['re_time'] = CommonService::Timecountdown($time, $group_one['expire_time']);

                    $group_one['one_title'] = $group_one['group_num'] - $group_one['current_group_num'];
                    $act['group_one'] = $group_one;
                } else {
                    $act['group_one'] = '';
                }
                if (count($group) >= 1) {
                    //有点复杂
                    if ($group[0]['status'] != 1) {
                        unset($group[0]);

                    } else {
                        if (count($group) == 1) {
                            $act['group_one'] = "";
                        }
                    }
                    $group_all = $group;
                    $gid = array_column($group_all, 'id');

                    $uid = Order::find()->select('user_id,group_id')->where(['group_id' => $gid])->asArray()->all();
                    $uidarr = array_column($uid, 'user_id');
                    $uidresult = User::find()->select('id,avatarurl')->where(['id' => $uidarr])->asArray()->all();
                    $result = [];
                    foreach ($uid as $key => $info) {
                        $result[$info['group_id']][] = $info;
                    }

                    $newgroup = [];
                    foreach ($result as $key => $reinfo) {
                        $uidstr = [];
                        foreach ($reinfo as $newinfo) {
                            foreach ($uidresult as $merge) {
                                if ($newinfo['user_id'] == $merge['id']) {
                                    $merge['new_avatar'] = GlobalUrlService::buildCdnUrl($merge['avatarurl']);
                                    $uidstr[] = $merge;
                                }
                            }
                        }
                        $userData['group_id'] = $reinfo[0]['group_id'];
                        $userData['user'] = $uidstr;
                        $newgroup[] = $userData;
                    }
                    foreach ($group_all as $val) {
                        $NewArr['group'] = $val;
                        $NewArr['group_end'] = $val['group_num'] - $val['current_group_num'];
                        foreach ($newgroup as $users) {
                            if ($val['id'] == $users['group_id']) {
                                $NewArr['users'] = $users;
                            }
                        }
                        $groupArr[] = $NewArr;
                    }
                    $act['group_all'] = $groupArr;
                } else {
                    $act['group_all'] = "";
                }
                //多少人在拼团，多少人已成团
                $groupend = (count($groupArr) == 0 ? 0 : count($groupArr)) * $group_one['group_num'];
                $act['group_title'] = $group_one['current_group_num'] . '人在拼团' . ',' . $groupend . '人已成团';
            } else {

                $act['group_one'] = "";
                $act['group_all'] = "";
                $act['group_title'] = '0人再拼团,0人已成团';
            }
            return $this->renderJson($act,'',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 详情页更多推荐
     */
    public function actionGetMore(){
        if($this->isGet()) {
            $id = $this->get('id');
            $data = Active::find()->select('id,active_name,goods_img,max_price,min_price,type')
                ->andWhere(['!=', 'id', $id])
                ->andWhere(['>', 'type', '0'])
                ->andWhere(['status' => 1])
                ->andWhere(['is_del' => 0])
                ->andWhere(['>', 'end_time', time()])
                ->asArray()
                ->all();

            if (count($data) <= 6) {
                $lists = $data;
            } else {
                $temp = array_rand($data, 6);
                foreach ($temp as $val) {
                    $lists[] = $data[$val];
                }
                unset($val);
            }

            $new_goods_attrs = [];
            if(!empty($lists)){
                $active_id = array_column($lists,'id');
                $active_attrs = ActiveAttr::find()
                    ->select(['active_id','original_price'])
                    ->where(['active_id'=>$active_id])
                    ->asArray()
                    ->all();
                $arr = [];
                foreach ($active_attrs as $attr){
                    if(in_array($attr['active_id'],$arr)){
                        array_push($arr,$attr['active_id']);
                    }
                    $new_goods_attrs[$attr['active_id']][] = $attr['original_price'];
                }
                unset($attr);
                foreach ($new_goods_attrs as $key=>$attr){
                    arsort($attr);
                    $new_goods_attrs[$key] = max($attr);
                }
                unset($attr);
            }
            foreach ($lists as &$list){
                $list['goods_img'] = GlobalUrlService::buildCdnUrl($list['goods_img']);
                if(isset($new_goods_attrs[$list['id']]) && !empty($new_goods_attrs[$list['id']])){
                    $list['max_price'] = $new_goods_attrs[$list['id']];
                }
            }

            return $this->renderJson($lists, '', ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 活动属性新接口
     */
    public function actionGetActiveAttr(){
        $type = $_REQUEST['type'];//1拼团   //2单独购买
        $id = $_REQUEST['aid'];
        if(!$id || !$type){
            return $this->renderJson([],'缺少参数',ConstantService::$response_fail);
        }
        $query = ActiveAttr::find();
        $query->andWhere(['active_id'=>$id]);
        $query->andWhere(['is_del'=>0]);

        $attrlist = $query->asArray()->all();

        $vid = [];
        foreach ($attrlist as $key=>&$val){
            $newid = explode('-',$attrlist[$key]['attribute_value_id']);
            $val['attr_img'] = GlobalUrlService::buildCdnUrl($val['attr_img']);
            foreach ($newid as $ids){
                if($ids > 0 && !in_array($ids,$vid)){
                    $vid[] = $ids;
                }
            }
            if($attrlist[$key]['inventory'] == 0){
                unset($attrlist[$key]);
            }

        }
        if(empty($attrlist)){
            return $this->renderJson([],'已售罄！',ConstantService::$response_fail);
        }
        unset($val);
        $attrlist = array_values($attrlist);
        $attrone = [];
        if(count($attrlist) == 1){
            $attrone = $attrlist[0];
        }

        $attributevalue = AttributeValue::find()->where(['id'=>$vid])->asArray()->all();
        $newvdata = [];
        foreach ($attributevalue as $val){
            $newvdata[$val['attr_name']][] = $val;
        }

        $valdata = array();
        foreach ($newvdata as $key=>$nval){
            $newval['name'] = $key;
            $newval['val'] = $nval;
            $valdata[] = $newval;
        }

        $goods['list_img'] = $attrlist[0]['attr_img'];


        //活动总库存
        $attr = ActiveAttr::find()->select('inventory,original_price,collage_price')->where(['active_id' => $id])->asArray()->all();
        $goods['money'] = '0';
        if(isset($attr) && !empty($attr)){
            $original_price = array_column($attr,'original_price');
            $collage_price = array_column($attr,'collage_price');
            $max_price = max($original_price);
            $min_price = min($collage_price);
            $goods['money'] = $min_price.'~'.$max_price;
            if($max_price == $min_price){
                $goods['money'] = $min_price;
            }
        }
        $goods['type'] = $type;
        $goods['attrlist'] = $valdata;
        $goods['attrone'] = $attrone;
        //新增的
        $goods['active_attr'] = $attrlist;
        return $this->renderJson($goods,'',ConstantService::$response_success);
    }

    /**
     * 选择属性后的价格
     */
    public function actionGetAttrmoney(){
        $attr_id = $this->get('attr_id');
        $aid =  $this->get('active_id');

        $query = ActiveAttr::find();

        $query->andWhere(['active_id'=>$aid]);
        $query->andWhere(['is_del'=>0]);
        $query->andWhere(['like','attribute_value_id',$attr_id]);

        $active = $query->asArray()->all();
        if($active){
            $attrids = '';
            foreach ($active as &$item){
                $ids = str_replace('-',',',$item['attribute_value_id']);
                $attrids = $attrids.','.$ids ;
            }
            unset($item);
            $attrids = explode(',',$attrids);
            $attrids = array_splice($attrids,1);
            $attribute_ids = array_unique($attrids);
            //删除 0 和当前已经选中
            foreach ($attribute_ids as $key=>$item){
                if($item == $attr_id || $item == 0){
                    unset($attribute_ids[$key]);
                }
            }
            unset($item);
            return $this->renderJson(['data'=>$active,'id'=>array_values($attribute_ids)],'',ConstantService::$response_success);
        } else {
            return $this->renderJson(['data'=>[],'id'=>[]],'',ConstantService::$response_success);
        }
    }

    /**
     * 付款详情页
     */
    public function actionPaymentInfo(){
        $get = $this->get();
        $attr_id = $get['attr_id'];
        $num = $get['num'];
        $type = $get['type'];//1拼团   //2单独购买
        $addr_id = $get['addr_id'];

        if(!$attr_id || !$type){
            return $this->renderJson([],'缺少参数',ConstantService::$response_fail);
        }

        $addmodel = new Address();

        if(isset($addr_id) && !empty($addr_id)){
            $data['address'] = $addmodel->GetAddressList($this->user['id'],$addr_id);
        } else {
            $data['address'] = $addmodel->GetAddressList($this->user['id']);
        }
        //活动属性
        $act_attr = ActiveAttr::find()->where(['id'=>$attr_id])->asArray()->one();

        $attr_value = GoodsService::getCurrentArrt([$attr_id]);

        if(isset($attr_value) && !empty($attr_value)){
            $data['attr_value'] = array_values($attr_value);
        }

//        $vid = explode('-',$act_attr['attribute_value_id']);
//        $aval = AttributeValue::find()->where(['id'=>$vid])->asArray()->all();
//        $attrval = array_column($aval,'value');
//        $data['attr_value'] = implode(':',$attrval);
        //活动
        $activity = Active::find()->select('id,goods_id,active_name,goods_id,shop_id')->where(['id'=>$act_attr['active_id']])->asArray()->one();

        //商品运费
        $goodsdata = Goods::find()->select('freight')->where(['id'=>$activity['goods_id']])->asArray()->one();
        $data['freight'] = $goodsdata['freight'];
//            //商家
        $data['num'] = $num;
        $data['goods_attr_id'] = $attr_id;
        $data['attr_img'] = GlobalUrlService::buildCdnUrl($act_attr['attr_img']);
        $data['inventory'] = $act_attr['inventory'];
        $data['active_name'] = $activity['active_name'];
        $lenth = mb_strlen($activity['active_name']);
        if($lenth > 26){
            $data['active_name'] = mb_substr($activity['active_name'],0,26).'...';
        }
        $data['active_id'] = $activity['id'];
        $data['goods_id'] = $activity['goods_id'];
        if($type == 1){
            $data['money'] = $act_attr['collage_price'];
        } else {
            $data['money'] = $act_attr['one_price'];
        }
        $data['shop'] = $this->_GetShopInfo($activity['shop_id']);
        return $this->renderJson($data,'',ConstantService::$response_success);
    }

    /**
     * 判断库存接口
     */
    public function actionGetInventory(){
        $num = $this->get('num');
        $id = $this->get('attr_id');
//        $id = $_GET['id'];
//        $num = $_GET['num'];
        $adata = ActiveAttr::findOne(['id'=>$id]);

        if($num > $adata['inventory']){
            return $this->renderJson([],'库存不足',ConstantService::$response_fail);
        } else {
            return $this->renderJson([],'',ConstantService::$response_success);
        }
    }

    /**
     * 商家信息
     * @param $id
     */
    private function _GetShopInfo($id){
        $shop = Shop::find()->select('shop_logo,shop_name,id')->where(['id'=>$id])->asArray()->one();
        $shop['shop_logo'] = $shop['shop_logo']?GlobalUrlService::buildCdnUrl($shop['shop_logo']):GlobalUrlService::buildCdnUrl('345734401912161877158695623.png');
        $act = $shop;
        $shopCount = Order::find()->select('sum(goods_num) as num')->where(['shop_id'=>$id,'pay_status'=>1])->asArray()->one();
        $act['count'] = $shopCount['num']?$shopCount['num']:0;
        return $act;
    }
    /**
     * 验证
     * @param array $data
     * @return bool|string
     */
    private function _validation($data = array()){
        if(empty($data['name'])){
            return "收货人不能为空";
        }
        if(empty($data['mobile'])){
            return "手机号不能为空";
        }
        if(empty($data['district'])){
            return "详细地址不能为空";
        }
        if(empty($data['city'])){
            return "收货地址不正确";
        }
        if(empty($data['province'])){
            return "收货地址不正确";
        }
        if(empty($data['area'])){
            return "收货地址不正确";
        }
        return true;
    }


}